/**
 * 
 */
package org.conan.groupapp.system.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.conan.groupapp.framework.dao.IBaseDao;
import org.conan.groupapp.framework.entity.PageData;
import org.conan.groupapp.framework.service.impl.BaseServiceImpl;
import org.conan.groupapp.system.dao.IAuthorityDao;
import org.conan.groupapp.system.dao.IRoleAuthorityDao;
import org.conan.groupapp.system.dao.IRoleDao;
import org.conan.groupapp.system.dao.IUserDao;
import org.conan.groupapp.system.dao.IUserRoleDao;
import org.conan.groupapp.system.entity.Authority;
import org.conan.groupapp.system.entity.Role;
import org.conan.groupapp.system.entity.RoleAuthority;
import org.conan.groupapp.system.entity.User;
import org.conan.groupapp.system.entity.UserRole;
import org.conan.groupapp.system.service.IRoleService;
import org.conan.groupapp.system.service.IUserService;
import org.conan.groupapp.util.OperLogToRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 *
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
	
	@Autowired
	@Qualifier("userDaoImpl")
	private IUserDao iUserDao;
	
	@Autowired
	@Qualifier("roleDaoImpl")
	private IRoleDao iRoleDao;

	@Autowired
	@Qualifier("roleServiceImpl")
	private IRoleService iRoleService;
	
	@Autowired
	@Qualifier("userRoleDaoImpl")
	private IUserRoleDao iUserRoleDao;
	
	@Autowired
	@Qualifier("authorityDaoImpl")
	private IAuthorityDao iAuthorityDao;
	
	@Autowired
	@Qualifier("roleAuthorityDaoImpl")
	private IRoleAuthorityDao iRoleAuthorityDao;
	
	public static int GENDER_MALE = 1;//男性
	public static int GENDER_FAMALE = 2;//女性
	
	public static String GENDER_MALE_STR = "男";
	public static String GENDER_FAMALE_STR = "女";
	
	public static int STAUTS_AVAILABLE = 1;//正常
	public static int STAUTS_UNAVAILABLE = 2;//停用
	
	public static String STAUTS_AVAILABLE_STR = "正常";
	public static String STAUTS_UNAVAILABLEE_STR = "停用";
	
	public static int USER_TYPE_ADMIN = 1;//超级用户
	public static int USER_TYPE_OTHER = 2;//普通用户
	
	public static String USER_TYPE_ADMIN_STR = "超级用户";
	public static String USER_TYPE_OTHER_STR = "普通用户";
	
	
	@Override
	@Resource(name = "userDaoImpl")
	public void setiBaseDao(IBaseDao<User> iBaseDao) {
		this.iBaseDao = iBaseDao;
	}
	
	
	@Override
	@OperLogToRecord
	public User save(User t) throws Exception {
		return super.save(t);
	}

	@Override
	@OperLogToRecord
	public User modify(User t) throws Exception {
		return super.modify(t);
	} 
	
	@Override
	@OperLogToRecord
	public int remove(Integer pirmaryKey) throws Exception {
		return super.remove(pirmaryKey);
	} 
	
	@SuppressWarnings("unchecked")
	@Override
	public PageData convertPageList(PageData pd){
		List<User> newList = new ArrayList<User>();
		for (User user : (List<User>)pd.getRows()) {
			newList.add(user);
		}
		pd.setRows(newList);
//		pd.setTableTitle(TAB_TITLE);
//		pd.setPageUrl(PAGE_URL);
		return pd;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public String toPageJson(PageData pd) {
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> big = new HashMap<String,Object>();
		big.put("count", pd.getTotalRecords());
		for (Map map : (List<Map>)pd.getRows()) {
			
		}
		big.put("rows", (List<Map>)pd.getRows());
		
		String s = "";
		try {
			s = mapper.writeValueAsString(big);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(s);
		return s;
	}
	
	@Override
	public Set<Authority> selectAuthoritiesByUsername(String username) throws Exception{
		Set<Authority> auList = new HashSet<Authority>();
		User user = selectUserByUsername(username);
		if(user!=null){
			UserRole ru = new UserRole();
			ru.setUserId(user.getUserId());
			List<UserRole> urList = iUserRoleDao.selectByCondition(ru, 0, Integer.MAX_VALUE);
			for (UserRole userRole : urList) {
				Role role = iRoleService.selectByPrimaryKey(userRole.getRoleId());
				if(role!=null){
					RoleAuthority ra = new RoleAuthority();
					ra.setRoleId(role.getRoleId());
					List<RoleAuthority> raList = iRoleAuthorityDao.selectByCondition(ra, 0, Integer.MAX_VALUE);
					for (RoleAuthority roleAuthority : raList) {
						Authority a = new Authority();
						a.setAuthId(roleAuthority.getAuthId());
						List<Authority> aList = iAuthorityDao.selectByCondition(a, 0, Integer.MAX_VALUE);
						auList.addAll(aList);
					}
				}
			}
		}
		return auList;
	}
	@Override
	public User selectUserByUsername(String username) throws Exception{
		User user = new User();
		user.setUsername(username);
		List<User> uList = iUserDao.selectByCondition(user, 0, Integer.MAX_VALUE);
		if(uList != null && uList.size()>0){
			return uList.get(0);
		}
		return null;
	}
	
	@Override
	public String loadMenu2Json(Integer authId,User user) throws Exception {
		String json = "";
		
		//获取登录用户的所有menu
		Set<Authority> auSet = new HashSet<Authority>();
		if(user.getUserType() == USER_TYPE_ADMIN){
			Authority au = new Authority();
			if(authId!=null && authId==0){
				au.setParentId(0);
			}else if(authId==null){
				au.setParentId(-1);
			}else{
				au.setParentId(authId);
			}
			List<Authority> rList = iAuthorityDao.selectByCondition(au, 0, Integer.MAX_VALUE);
			for (Authority authority : rList) {
				auSet.add(authority);
			}
		}else{
			UserRole ur = new UserRole();
			ur.setUserId(user.getUserId());
			List<UserRole> rList = iUserRoleDao.selectByCondition(ur, 0, Integer.MAX_VALUE);
			for (UserRole userRole : rList) {
				Role role = iRoleService.selectByPrimaryKey(userRole.getRoleId());
				if(role!=null){
					RoleAuthority ra = new RoleAuthority();
					ra.setRoleId(role.getRoleId());
					List<RoleAuthority> raList = iRoleAuthorityDao.selectByCondition(ra, 0, Integer.MAX_VALUE);
					for (RoleAuthority roleAuthority : raList) {
						Authority auth = iAuthorityDao.selectByPrimaryKey(roleAuthority.getAuthId());
						if(authId!=null && authId==0){
							if(auth.getParentId().intValue()==0){
								auSet.add(auth);
							}
						}else if(authId!=null && authId>0){
							if(auth.getParentId().intValue() == authId.intValue()){
								auSet.add(auth);
							}
						}
					}
				}
			}
		}
		
		//生成json
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		for (Authority auth : auSet) {
			Map<String,String> map = new HashMap<String,String>();
			map.put("text", auth.getAuthName());
			map.put("id", auth.getAuthId().toString());
			if(authId == null || authId.intValue()==0){
				map.put("cls", "folder");
			}else{
				map.put("cls", "file");
				map.put("leaf", "true");
				map.put("canHref", "true");
			}
			map.put("href_url", auth.getAuthUrl());
			list.add(map);
		}
		ObjectMapper mapper = new ObjectMapper();
		json = mapper.writeValueAsString(list);
		System.out.println(json);
		return json;
	}
	
	/**
	 * 
	 * @param status
	 * @return
	 */
	public static String convertStatusToString(int status){
		if(status == STAUTS_AVAILABLE){
			return STAUTS_AVAILABLE_STR;
		}else if(status == STAUTS_UNAVAILABLE){
			return STAUTS_UNAVAILABLEE_STR;
		}
		return "";
	}
	/**
	 * 
	 * @param status
	 * @return
	 */
	public static String convertGenderToString(int gender){
		if(gender == GENDER_MALE){
			return GENDER_MALE_STR;
		}else if(gender == GENDER_FAMALE){
			return GENDER_FAMALE_STR;
		}
		return "";
	}
	
	/**
	 * 
	 * @param status
	 * @return
	 */
	public static String convertUserTypeToString(int userType){
		if(userType == USER_TYPE_ADMIN){
			return USER_TYPE_ADMIN_STR;
		}else if(userType == USER_TYPE_OTHER){
			return USER_TYPE_OTHER_STR;
		}
		return "";
	}

	public IUserDao getiUserDao() {
		return iUserDao;
	}

	public void setiUserDao(IUserDao iUserDao) {
		this.iUserDao = iUserDao;
	}


	public IRoleDao getiRoleDao() {
		return iRoleDao;
	}


	public void setiRoleDao(IRoleDao iRoleDao) {
		this.iRoleDao = iRoleDao;
	}


	public IUserRoleDao getiUserRoleDao() {
		return iUserRoleDao;
	}


	public void setiUserRoleDao(IUserRoleDao iUserRoleDao) {
		this.iUserRoleDao = iUserRoleDao;
	}


	public IAuthorityDao getiAuthorityDao() {
		return iAuthorityDao;
	}


	public void setiAuthorityDao(IAuthorityDao iAuthorityDao) {
		this.iAuthorityDao = iAuthorityDao;
	}


	public IRoleAuthorityDao getiRoleAuthorityDao() {
		return iRoleAuthorityDao;
	}


	public void setiRoleAuthorityDao(IRoleAuthorityDao iRoleAuthorityDao) {
		this.iRoleAuthorityDao = iRoleAuthorityDao;
	}


	public IRoleService getiRoleService() {
		return iRoleService;
	}


	public void setiRoleService(IRoleService iRoleService) {
		this.iRoleService = iRoleService;
	}


	

	
	
}
